package wwl.lsf.hellospringboot.baidu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Title
 * @Author wangwenliang
 * @Date 2020/6/23
 * @Description
 */
@Controller
@RequestMapping("/img2text")
@Slf4j
public class Img2TextController {

  @ResponseBody
  @RequestMapping("/baidu")
  public String change(@RequestBody JSONObject jsonObject2) {
    String img = jsonObject2.getString("html");
    log.info("img-html:{}", img);
    Document doc = Jsoup.parse(img);
//    System.out.println(doc); // 输出带标签的html文档
//    System.out.println("---------------------\n" + doc.text()); // 输出内容
    Elements element = doc.getElementsByTag("img");
    StringBuilder stringBuilder = new StringBuilder();
    element.forEach(element1 -> {
      String html = element.get(0).attr("src");
      String s = StringUtils.substringAfter(html, ",");
      log.info("请求参数:{}",s);
      String result = GeneralBasic.generalBasic(s);
      JSONObject jsonObject = JSONObject.parseObject(result);
      List<JSONObject> words_result = (List) jsonObject.get("words_result");
      if (CollectionUtils.isNotEmpty(words_result)) {
        words_result.forEach(i -> {
          stringBuilder.append(i.get("words")).append("\r\n");
        });
      }
      stringBuilder.append("\r\n");
    });
    String s = JSON.toJSONString(stringBuilder);
    System.out.println("s = " + s);
    return s;
  }

}
